
import socket,re,xchat

__module_name__ = "mpd-xchat"
__module_version__ = "0.1"
__module_description__ = "xchat interface to mpd"

def mpd_connect():
    mpd=socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
    host='127.0.0.1'
    port=6600
    mpd.connect((host,port))
    welcome=mpd.recv(1024)
    return mpd

def status_check(mpd_socket):
    mpd_socket.send('status\r\n')
    status_reply = mpd_socket.recv(1024)
    status = re.findall(r'state[:]\s[\S]+', status_reply)[0].split(':')[1]
    if status==' stop':
        return False
    else:
        return True

def playing(word, word_eol, userdata):
    mpd = mpd_connect()
    if status_check(mpd):
        mpd.send('currentsong\r\n')
        data=mpd.recv(1024)
        artist=re.findall(r'Artist[:]\s.+',data)[0].split(':')[1]
        title=re.findall(r'Title[:]\s.+',data)[0].split(':')[1]
        msg='Now playing:'+artist+' - '+title
        xchat.command('me '+msg)
    else:
        print 'No song playing'
    mpd.close()
    return xchat.EAT_ALL

    
#hooks into the show xchat command
xchat.hook_command("show",playing)

